import React from "react";
import HistoryScore from "../../../../Common/svg/HistoryScore";
// import Sequence from "../../../../Common/svg/Sequence";
// import UnlockPayment from "../../../../Component/UnlockPayment";
import './index.css';
// import RedStar from "../../../../Component/RedStar";
import QuestingSelecter from "../../../../Component/QuestingSelecter";
import Examination from "../../../../Server/Study/Examination";
// import MessageUtil from "../../../../utils/MessageUtil";
import TestCountdown from "../../../../Component/TestCountdown";
import UserCheck from "../../../../utils/UserCheck";
import TimeUtil from "../../../../utils/TimeUtil";
import StudyLayout from "../../../../Layout/StudyLayout/StudyLayout";

export default class  extends React.Component{
    
    constructor(props){
        super();
        let number=props.match.params.number;
        let isOrder=(number!=="-1" && number!=="-99");//是否为随机考试
        let title="";
        if(isOrder){
            title="理论模拟测试"+number;
        }
        this.state={
            questions:[],
            number,
            isOrder,//是否为顺序考试
            result:[],//选择的结果
            currectAnswer:[],//所有题目的正确答案
                        
            currect:[],//计算结果所有选中的正确答案
            error:[],//所有选错的题目答案
            time:60*60,
            questionCount:0,
            totalCount:0,
            startTime:new Date(),
            title
        };
        
        //非中断后继续考试
        //获取服务端数据
        if(!isOrder){
            if(number==="-99"){
                title="错题考试";

                this.ErrorTest();
            }
            else{
                title="随机考试";

                this.RandomTest();
            }
        }
        else{
            this.OrderTest(number);
        }
        this.state.title=title;
    }
    ErrorTest(){
        Examination.WrongExam(UserCheck.GetUserID())
        .then(response=>{
            this.RenderQuestion(response.data);
        })
    }
    RandomTest(){
        Examination.RandomTest()
        .then(response=>{
            this.RenderQuestion(response.data);
        })
    }
    OrderTest(number){
        Examination.OrederTest(number)
        .then(response=>{
            this.RenderQuestion(response.data);
        })
    }

    RenderQuestion(arrayData){
        let questions=[];
        let isRadio=true;
            let index=0;
            // console.log(arrayData)

            // console.log(arrayData.length)
            if(arrayData.length===0){
                return;
            }
            let numberIndex=1;
            arrayData.forEach(item => {
                if(item!==null){
                    let questionNumber=item.questionNumber;
                    let title=item.questionTitle;
                    Examination.SelectQuestionChapterNumberDetails(0,item.questionId,questionNumber)
                    .then(response=>{
                        try{
                            let answers=[];
                            response.data.PilotAnswers.forEach(element => {
                                answers.push({
                                    value:element.answerText,
                                    key:element.options
                                })
                            });
    
                            let currectAnswer=this.state.currectAnswer;
                            
                            currectAnswer[questionNumber]={
                                questionNumberId:response.data.PilotParse.id,
                                questionNumber:questionNumber,
                                questionId:response.data.PilotParse.questionId,
                                answer:response.data.PilotParse.answer
                            }
                            let showQuestionNumer=this.state.isOrder?numberIndex:questionNumber;
                            let selectValue=this.GetQuestionSelect(showQuestionNumer);
                            // console.log(showQuestionNumer)
                            // console.log(selectValue)

                            if(isRadio){
                                // console.log(questionNumer)
                                // console.log(this.state.result[questionNumer])
                                let info=(
                                    <div className="MockExamStartExam_Questing" key={index++}>
                                        <QuestingSelecter isDisabled={false} selectedValue={selectValue} change={e=>this.Change(e)} 
                                        type="radio" number={showQuestionNumer} question={title} answers={answers}/>
                                    </div>);
    
                                questions.push({
                                    questionNumber:showQuestionNumer,
                                    node:info
                                });
                            }
                            else{
                                let info=(<div className="MockExamStartExam_Questing" key={index++}>
                                    <QuestingSelecter isDisabled={false} selectedValue={selectValue} change={e=>this.Change(e)} 
                                    type="checkbox" number={showQuestionNumer} question={title} answers={answers}/>
                                    </div>);
                                questions.push({
                                    questionNumber:showQuestionNumer,
                                    node:info
                                    }
                                );
                            }
                            numberIndex++;
                            //sort
                            if(this.state.number!=="-1"){
                                questions.sort((x,y)=>{
                                    return x.questionNumber>y.questionNumber?1:-1;;
                                });
                            }
                            
    
                            let tmp=[];
                            questions.forEach(element => {
                                tmp.push(element.node);
                            });
                            this.setState({
                                questions:tmp,
                                questionCount:arrayData.length,
                                totalCount:arrayData.length,
                                currectAnswer
                            },()=>{
                                // console.log(currectAxnswer)
                                this.LoadData();
                                // MessageUtil.ChangeHeight();
                            });
                        }
                        catch{

                        }
                    });
                }
            });
    }
    GetQuestionSelect(number){
        let storage=localStorage.getItem(this.state.title);

        if(this.state.isOrder){

            if(storage!==undefined&&storage!==null){
                let data=JSON.parse(localStorage.getItem(this.state.title));
                // console.log(data.result);
                return data.result[number];
            }
        }
        return undefined;
    }
    LoadData(){
        let storage=localStorage.getItem(this.state.title);
        if(this.state.isOrder){
            if(storage!==undefined&&storage!==null){
                let data=JSON.parse(localStorage.getItem(this.state.title));
                // console.log(data);
                this.setState({
                    result:data.result,//选择的结果
                    currectAnswer:data.currectAnswer,//所有题目的正确答案
                    
                    currect:data.currect,//计算结果所有选中的正确答案
                    error:data.error,//所有选错的题目答案
                    time:data.time,
                    questionCount:data.questionCount,
                    totalCount:data.totalCount,
                    startTime:new Date(data.startTime),
                },()=>{
                    // MessageUtil.ChangeHeight();
                });
            }
        }
    }

    Change(value){
        let result=this.state.result;
        // console.log(result)
        result[value.number]=value.value;
        let count=0;
        // console.log(result)
    
        result.forEach(element => {
            if(element!==null){
                count++;
            }
        });
        if(this.state.totalCount-count>=0){
            this.setState({
                result,
                questionCount:this.state.totalCount-count
            });
        }
    }
    
    Time(){
        let time=this.state.time;
        if(time>0){
            this.setState({
                time:time-1
            },()=>{
                // console.log(this.state.time)
            });
        }
        else{
            // 强制交卷
            this.FinishTest();
        }
    }
    CalcGrade(){
        let wrongTest=[];
        let currectAnswer=this.state.currectAnswer;
        let result=this.state.result;
        let currect=[];
        let error=[];

        let currectCount=0;
        // console.log(currectAnswer)
        for(let i in currectAnswer){
            // console.log(i)
            if(currectAnswer[i]===null){
                continue;
            }
            if( result[i]===currectAnswer[i].answer){
                currect[i]=currectAnswer[i];
                currectCount++;
            }
            else{
                let errorSelect=result[i]===undefined?"":result[i];
                // console.log(errorSelect);
                error[i]=errorSelect;
                wrongTest.push({
                    questionNumberId:currectAnswer[i].questionNumberId,
                    questionNumber:currectAnswer[i].questionNumber,
                    questionId:currectAnswer[i].questionId,
                    wrongAnswer:errorSelect,
                    answer:currectAnswer[i].answer
                })
            }
        }
        // console.log(currect)
        // console.log(error)

        this.setState({
            currect,
            error
        });
        
        let grade=(currectCount/this.state.totalCount)*100;
        return {grade,wrongTest};
    }
    FinishTest(){
        let title="";
        if(this.state.isOrder){
            title="顺序考试"+this.state.number;
        }
        else{
            if(this.state.number==="-1"){
                title="随机考试";
            }
            if(this.state.number==="-99"){
                title="随机考试";
            }
        }
        
        let calcResult=this.CalcGrade();
        let wrongtest=JSON.stringify(calcResult.wrongTest);
        let grade=calcResult.grade;

        // console.log(this.state.startTime)

        Examination.SubmitPaper(UserCheck.GetUserID(),grade,TimeUtil.Date2Str(this.state.startTime) ,title,wrongtest)
        .then(response=>{
            // console.log(response)
        });
    }
    ParseExam(){
        let arr=this.state;
    　　 localStorage.setItem(this.state.title,JSON.stringify(arr)); 
    }
    componentDidMount(){
        setInterval(() => {
            this.Time()
        }, 1000);

    }
    render(){
        let showDiv=(
            <div className="Courseware_Body" >
               <div className="Courseware_Middle">
                    <div className="Courseware_Middle_mulu">{this.state.title}</div>
                    <div className="Courseware_Middle_right">
                        <span><HistoryScore/></span><span><font color="#5393EB">历史成绩</font></span>
                    </div>
                </div>
                <div>
                    {this.state.questions}
                </div>
                <TestCountdown text="Fly派" subtext="什么什么介绍等等..." finishExam={e=>this.FinishTest(e)} parseExam={e=>this.ParseExam(e)} question_num={this.state.questionCount} countdown={this.state.time}/>
            </div>
        );
        return(
            <StudyLayout content={showDiv} Exam={true}/>
        );
    }
}